package ace.cmp.security.oauth2.resource.server.test.autoconfig;

import ace.cmp.security.oauth2.resource.server.autoconfig.config.Oauth2ResourceServerSecurityServiceAutoConfigure;
import ace.cmp.security.oauth2.resource.server.test.properties.MockOpaqueTokenIntrospectorProperties;
import ace.cmp.security.oauth2.resource.server.test.service.MockTokenIntrospectService;
import ace.cmp.security.oauth2.resource.server.test.service.impl.MockTokenIntrospectServiceImpl;
import ace.cmp.security.oauth2.resource.server.test.service.impl.NoneMockTokenIntrospectServiceImpl;
import lombok.AllArgsConstructor;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;

/**
 * @author caspar
 * @date 2023/2/6 20:09 自动配置单元测试
 */
@EnableConfigurationProperties({MockOpaqueTokenIntrospectorProperties.class})
@AutoConfigureBefore({Oauth2ResourceServerSecurityServiceAutoConfigure.class})
@AllArgsConstructor
@Configuration
public class SecurityOAuth2ResourceServerTestAutoConfigure {
  @ConditionalOnProperty(
      havingValue = "true",
      value = MockOpaqueTokenIntrospectorProperties.PREFIX + ".enable",
      matchIfMissing = true)
  @Bean
  @ConditionalOnMissingBean
  public OpaqueTokenIntrospector introspector() {
    return Mockito.mock(OpaqueTokenIntrospector.class);
  }

  @ConditionalOnProperty(
      havingValue = "true",
      value = MockOpaqueTokenIntrospectorProperties.PREFIX + ".enable",
      matchIfMissing = true)
  @Bean
  @ConditionalOnMissingBean
  public MockTokenIntrospectService mockUserService(OpaqueTokenIntrospector introspector) {
    return new MockTokenIntrospectServiceImpl(introspector);
  }

  @ConditionalOnProperty(
      havingValue = "false",
      value = MockOpaqueTokenIntrospectorProperties.PREFIX + ".enable",
      matchIfMissing = false)
  @Bean
  @ConditionalOnMissingBean
  public MockTokenIntrospectService noneMockUserService() {
    return new NoneMockTokenIntrospectServiceImpl();
  }
}
